#include "CheckBoxToHeaderView.h"
#include <QPainter>
#include <QMouseEvent>

CheckBoxToHeaderView::CheckBoxToHeaderView(Qt::Orientation orientation, QWidget* parent )
: QHeaderView(orientation, parent), m_stateChanged(false), m_checkState(Qt::Unchecked), m_state(QStyle::State_Off)
{
}

CheckBoxToHeaderView::~CheckBoxToHeaderView()
{
}
void CheckBoxToHeaderView::paintEvent(QPaintEvent* e)
{
    if (m_stateChanged) {
        m_stateChanged = false;
        m_stateChanged = true;
        switch (m_checkState) {
        case Qt::Unchecked:
            m_state = QStyle::State_Off;
            break;
        case Qt::Checked:
            m_state = QStyle::State_On;
            break;
        default:
            m_state = QStyle::State_NoChange;
            break;
        }
    }
    QHeaderView::paintEvent(e);
}

void CheckBoxToHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);
    painter->restore();
    if (logicalIndex == 0) {
        QStyleOptionButton button;
        button.rect = QRect(rect.width() / 2 - 8, rect.height() / 2 - 8, 16, 16);
        button.state = m_state;
        style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &button, painter);
    }
}

void CheckBoxToHeaderView::mousePressEvent(QMouseEvent* e)
{
    int column = logicalIndexAt(e->pos());
    if (column == 0) {
        m_stateChanged = true;
        m_checkState = m_checkState == Qt::Unchecked ? Qt::Checked : Qt::Unchecked;
        toggled(m_checkState);
        viewport()->update();
    }
    QHeaderView::mousePressEvent(e);
}

void CheckBoxToHeaderView::setCheckState(Qt::CheckState checkState)
{
    m_checkState = checkState;
    m_stateChanged = true;
}
